const { sequelize } = require('../models');
const { Admin, Role, Permission, AdminRole, RolePermission } = require('../models');
const logger = require('../utils/logger');

async function createAdminTables() {
  try {
    console.log('开始创建管理员系统表...');

    // 创建表
    await sequelize.sync({ force: false });
    console.log('✓ 数据库表创建完成');

    // 检查是否已有初始数据
    const adminCount = await Admin.count();
    const roleCount = await Role.count();
    const permissionCount = await Permission.count();

    if (adminCount > 0 || roleCount > 0 || permissionCount > 0) {
      console.log('✓ 管理员系统已初始化，跳过数据初始化');
      return;
    }

    console.log('开始初始化管理员系统数据...');

    // 创建默认权限
    const permissions = [
      // 管理员管理
      { name: 'admin:read', displayName: '查看管理员', resource: 'admin', action: 'read', category: '管理员管理', isSystem: true },
      { name: 'admin:create', displayName: '创建管理员', resource: 'admin', action: 'create', category: '管理员管理', isSystem: true },
      { name: 'admin:update', displayName: '更新管理员', resource: 'admin', action: 'update', category: '管理员管理', isSystem: true },
      { name: 'admin:delete', displayName: '删除管理员', resource: 'admin', action: 'delete', category: '管理员管理', isSystem: true },

      // 角色管理
      { name: 'role:read', displayName: '查看角色', resource: 'role', action: 'read', category: '角色管理', isSystem: true },
      { name: 'role:create', displayName: '创建角色', resource: 'role', action: 'create', category: '角色管理', isSystem: true },
      { name: 'role:update', displayName: '更新角色', resource: 'role', action: 'update', category: '角色管理', isSystem: true },
      { name: 'role:delete', displayName: '删除角色', resource: 'role', action: 'delete', category: '角色管理', isSystem: true },

      // 权限管理
      { name: 'permission:read', displayName: '查看权限', resource: 'permission', action: 'read', category: '权限管理', isSystem: true },
      { name: 'permission:create', displayName: '创建权限', resource: 'permission', action: 'create', category: '权限管理', isSystem: true },
      { name: 'permission:update', displayName: '更新权限', resource: 'permission', action: 'update', category: '权限管理', isSystem: true },
      { name: 'permission:delete', displayName: '删除权限', resource: 'permission', action: 'delete', category: '权限管理', isSystem: true },

      // 用户管理
      { name: 'user:read', displayName: '查看用户', resource: 'user', action: 'read', category: '用户管理', isSystem: true },
      { name: 'user:update', displayName: '更新用户', resource: 'user', action: 'update', category: '用户管理', isSystem: true },
      { name: 'user:delete', displayName: '删除用户', resource: 'user', action: 'delete', category: '用户管理', isSystem: true },
      { name: 'user:points', displayName: '管理用户积分', resource: 'user', action: 'points', category: '用户管理', isSystem: true },

      // 商品管理
      { name: 'product:read', displayName: '查看商品', resource: 'product', action: 'read', category: '商品管理', isSystem: true },
      { name: 'product:create', displayName: '创建商品', resource: 'product', action: 'create', category: '商品管理', isSystem: true },
      { name: 'product:update', displayName: '更新商品', resource: 'product', action: 'update', category: '商品管理', isSystem: true },
      { name: 'product:delete', displayName: '删除商品', resource: 'product', action: 'delete', category: '商品管理', isSystem: true },

      // 订单管理
      { name: 'order:read', displayName: '查看订单', resource: 'order', action: 'read', category: '订单管理', isSystem: true },
      { name: 'order:update', displayName: '更新订单', resource: 'order', action: 'update', category: '订单管理', isSystem: true },
      { name: 'order:process', displayName: '处理订单', resource: 'order', action: 'process', category: '订单管理', isSystem: true },
      { name: 'order:refund', displayName: '订单退款', resource: 'order', action: 'refund', category: '订单管理', isSystem: true },

      // 积分管理
      { name: 'points:read', displayName: '查看积分记录', resource: 'points', action: 'read', category: '积分管理', isSystem: true },
      { name: 'points:adjust', displayName: '调整积分', resource: 'points', action: 'adjust', category: '积分管理', isSystem: true },

      // 广告管理
      { name: 'ad:read', displayName: '查看广告数据', resource: 'ad', action: 'read', category: '广告管理', isSystem: true },
      { name: 'ad:statistics', displayName: '广告统计分析', resource: 'ad', action: 'statistics', category: '广告管理', isSystem: true },

      // 系统管理
      { name: 'system:dashboard', displayName: '系统概览', resource: 'system', action: 'dashboard', category: '系统管理', isSystem: true },
      { name: 'system:statistics', displayName: '系统统计', resource: 'system', action: 'statistics', category: '系统管理', isSystem: true },
      { name: 'system:settings', displayName: '系统设置', resource: 'system', action: 'settings', category: '系统管理', isSystem: true }
    ];

    const createdPermissions = await Permission.bulkCreate(permissions);
    console.log(`✓ 创建了 ${createdPermissions.length} 个默认权限`);

    // 创建默认角色
    const roles = [
      {
        name: 'super_admin',
        displayName: '超级管理员',
        description: '拥有所有权限的超级管理员',
        level: 100,
        isSystem: true
      },
      {
        name: 'admin',
        displayName: '管理员',
        description: '普通管理员，拥有大部分管理权限',
        level: 80,
        isSystem: true
      },
      {
        name: 'operator',
        displayName: '运营人员',
        description: '运营人员，主要负责用户和订单管理',
        level: 60,
        isSystem: true
      },
      {
        name: 'customer_service',
        displayName: '客服人员',
        description: '客服人员，主要负责用户服务',
        level: 40,
        isSystem: true
      }
    ];

    const createdRoles = await Role.bulkCreate(roles);
    console.log(`✓ 创建了 ${createdRoles.length} 个默认角色`);

    // 为超级管理员分配所有权限
    const superAdminRole = createdRoles.find(role => role.name === 'super_admin');
    const allPermissionIds = createdPermissions.map(p => p.id);
    
    const superAdminPermissions = allPermissionIds.map(permissionId => ({
      roleId: superAdminRole.id,
      permissionId
    }));
    
    await RolePermission.bulkCreate(superAdminPermissions);
    console.log(`✓ 为超级管理员分配了所有权限`);

    // 为普通管理员分配权限（除了管理员管理权限）
    const adminRole = createdRoles.find(role => role.name === 'admin');
    const adminPermissions = createdPermissions
      .filter(p => !p.name.startsWith('admin:') && !p.name.startsWith('permission:'))
      .map(p => ({
        roleId: adminRole.id,
        permissionId: p.id
      }));
    
    await RolePermission.bulkCreate(adminPermissions);
    console.log(`✓ 为普通管理员分配了权限`);

    // 为运营人员分配权限
    const operatorRole = createdRoles.find(role => role.name === 'operator');
    const operatorPermissions = createdPermissions
      .filter(p => ['user:', 'order:', 'product:', 'points:', 'system:dashboard', 'system:statistics'].some(prefix => p.name.startsWith(prefix)))
      .map(p => ({
        roleId: operatorRole.id,
        permissionId: p.id
      }));
    
    await RolePermission.bulkCreate(operatorPermissions);
    console.log(`✓ 为运营人员分配了权限`);

    // 为客服人员分配权限
    const customerServiceRole = createdRoles.find(role => role.name === 'customer_service');
    const customerServicePermissions = createdPermissions
      .filter(p => ['user:read', 'user:update', 'order:read', 'order:update', 'system:dashboard'].includes(p.name))
      .map(p => ({
        roleId: customerServiceRole.id,
        permissionId: p.id
      }));
    
    await RolePermission.bulkCreate(customerServicePermissions);
    console.log(`✓ 为客服人员分配了权限`);

    // 创建默认超级管理员账户
    const superAdmin = await Admin.create({
      username: 'admin',
      password: 'admin123',
      email: 'admin@example.com',
      realName: '系统管理员',
      status: 'active'
    });

    // 为超级管理员分配角色
    await AdminRole.create({
      adminId: superAdmin.id,
      roleId: superAdminRole.id
    });

    console.log('✓ 创建了默认超级管理员账户');
    console.log('  用户名: admin');
    console.log('  密码: admin123');
    console.log('  请登录后立即修改默认密码！');

    console.log('✓ 管理员系统初始化完成');

  } catch (error) {
    console.error('创建管理员系统表失败:', error);
    logger.error('Create admin tables failed:', error);
    throw error;
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  createAdminTables()
    .then(() => {
      console.log('管理员系统表创建完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('创建失败:', error);
      process.exit(1);
    });
}

module.exports = createAdminTables;